package com.ruoyi.common.utils.file;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.extractor.POITextExtractor;
import org.apache.poi.hslf.usermodel.*;
import org.apache.poi.ooxml.extractor.ExtractorFactory;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xslf.usermodel.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
public class PPTUtils {

    /**
     * 解析PPT文件中的内容
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static String parsePpt(InputStream inputStream) throws IOException {
        XMLSlideShow ppt = new XMLSlideShow(inputStream);
        StringBuilder sb = new StringBuilder();
        for (XSLFSlide slide : ppt.getSlides()) {
            for (XSLFShape shape : slide.getShapes()) {
                if (shape instanceof XSLFTextShape) {
                    XSLFTextShape textShape = (XSLFTextShape) shape;
                    for (XSLFTextParagraph paragraph : textShape.getTextParagraphs()) {
                        for (XSLFTextRun run : paragraph.getTextRuns()) {
                            sb.append(run.getRawText());
                        }
                    }
                }
            }
        }
        return sb.toString();
    }

    /**
     * 从doc,docx,xls,xlsx,ppt,pptx类型文件中抽取文本
     *
     * @param file 文件
     * @return 文本
     **/
    public static String parsePpt(File file) {
        FileInputStream input = null;
        try {
            input = new FileInputStream(file);
            POITextExtractor extractor = ExtractorFactory.createExtractor(input);
            String content = extractor.getText();
            extractor.close();
            return content;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 从ppt, pptx类型文件中抽取文本
     *
     * @param file 文件
     * @return 文本
     */
    public static String parsePPT(File file) {
        FileInputStream input = null;
        StringBuilder contentBuilder = new StringBuilder();

        try {
            input = new FileInputStream(file);

            // 判断文件类型并创建相应的提取器
            if (file.getName().toLowerCase().endsWith(".ppt")) {
                log.debug("检测到PPT格式文件，使用HSLF解析器");
// 处理旧版PPT文件
                HSLFSlideShow ppt = new HSLFSlideShow(new POIFSFileSystem(input));
                int slideCount = ppt.getSlides().size();
                log.info("PPT文件包含{}张幻灯片", slideCount);
                for (int i = 0; i < slideCount; i++) {
                    HSLFSlide slide = ppt.getSlides().get(i);
                    log.debug("正在解析第{}张幻灯片", i + 1);
                    contentBuilder.append("\n");

                    // 获取所有形状
                    for (HSLFShape shape : slide.getShapes()) {
                        if (shape instanceof HSLFTextShape) {
                            HSLFTextShape textShape = (HSLFTextShape) shape;

                            // 使用静态方法获取段落文本
                            for (HSLFTextParagraph paragraph : textShape.getTextParagraphs()) {
                                log.debug("正在解析段落："+ paragraph);
                                String paragraphText = HSLFTextParagraph.getText(paragraph.getParentShape().getTextParagraphs());
                                contentBuilder.append(paragraphText).append("\n");
                            }

                        } else if (shape instanceof HSLFTable) {
                            // 提取表格内容
                            HSLFTable table = (HSLFTable) shape;
                            log.debug("在第{}张幻灯片中发现表格，行数：{}，列数：{}", i + 1,
                                    table.getNumberOfRows(), table.getNumberOfColumns());
                            contentBuilder.append("### 表格内容\n\n");

                            for (int row = 0; row < table.getNumberOfRows(); row++) {
                                for (int col = 0; col < table.getNumberOfColumns(); col++) {
                                    HSLFTableCell cell = table.getCell(row, col);
                                    if (cell != null) {
                                        String text = cell.getText();
                                        if (text != null && !text.trim().isEmpty()) {
                                            contentBuilder.append("| ").append(text.trim()).append(" ");
                                        }
                                    }
                                }
                                contentBuilder.append("|\n");

                                if (row == 0) {
                                    for (int col = 0; col < table.getNumberOfColumns(); col++) {
                                        contentBuilder.append("|---");
                                    }
                                    contentBuilder.append("|\n");
                                }
                            }
                        }
                    }
                    contentBuilder.append("\n");
                }
                ppt.close();
                log.info("PPT文件解析完成");
            } else if (file.getName().toLowerCase().endsWith(".pptx")) {

                // 处理新版PPTX文件
                XMLSlideShow pptx = new XMLSlideShow(input);
                for (XSLFSlide slide : pptx.getSlides()) {
                    contentBuilder.append("=== Slide ").append(slide.getSlideNumber()).append(" Start ===\n");
                    for (XSLFShape shape : slide.getShapes()) {
                        if (shape instanceof XSLFTextShape) {
                            XSLFTextShape textShape = (XSLFTextShape) shape;
                            for (XSLFTextParagraph paragraph : textShape.getTextParagraphs()) {
                                for (XSLFTextRun run : paragraph.getTextRuns()) {
                                    contentBuilder.append(run.getRawText());
                                }
                                contentBuilder.append("\n");
                            }
                        } else if (shape instanceof XSLFTable) {
                            // 提取表格内容
                            XSLFTable table = (XSLFTable) shape;
                            contentBuilder.append("Table Content:\n");
                            for (XSLFTableRow row : table.getRows()) {
                                for (XSLFTableCell cell : row.getCells()) {
                                    String text = cell.getText();
                                    if (text != null && !text.trim().isEmpty()) {
                                        contentBuilder.append(text.trim()).append("\t");
                                    }
                                }
                                contentBuilder.append("\n");
                            }
                        }
                    }
                    contentBuilder.append("=== Slide ").append(slide.getSlideNumber()).append(" End ===\n");
                }
                pptx.close();
            }

            return contentBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
